package com.ruoyi.web.controller.bussiness;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.entity.po.TJudges;
import com.ruoyi.entity.po.TPlayer;
import com.ruoyi.framework.web.service.MobileTokenService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.service.IJudgesService;
import com.ruoyi.service.IPlayerService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Set;

/**
 *
 *@author wangkk
 *@date 2025-02-11 13:50
 */
@RestController
@RequestMapping("/mobile")
@RequiredArgsConstructor
public class MobileLoginController {

    private final IPlayerService playerService;

    private final IJudgesService judgesService;

    private final MobileTokenService tokenService;

    /**
     * 登录方法
     *
     * @param loginVo 登录信息
     * @return 结果
     */
    @Anonymous
    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Valid @NotNull LoginVo loginVo) {
        if (loginVo.password.length() != 6 && !loginVo.phoneNum.endsWith(loginVo.password)) {
            return AjaxResult.error("账号或密码不正确");
        }
        final MobileTokenService.MobileUser mobileUser = new MobileTokenService.MobileUser();
        final TPlayer tPlayer = playerService.selectByPhoneNum(loginVo.phoneNum);
        int userType = 0;
        if (tPlayer != null) {
            userType = 2;
            mobileUser.setName(tPlayer.getName());
        }
        final TJudges tJudges = judgesService.selectByPhoneNum(loginVo.phoneNum);
        if (tJudges != null) {
            userType = 3;
            mobileUser.setName(tJudges.getNickName());
        }
        mobileUser.setUserType(userType);
        mobileUser.setPhoneNum(loginVo.phoneNum);
        return AjaxResult.success().put(Constants.TOKEN, tokenService.createToken(mobileUser));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo(HttpServletRequest request) {
        final MobileTokenService.MobileUser mobileUser = tokenService.getMobileUser(request);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("userType", mobileUser.getUserType());
        ajax.put("phoneNum", mobileUser.getPhoneNum());
        return ajax;
    }


    @Data
    public static class LoginVo {

        @NotBlank(message = "手机号不能为空")
        private String phoneNum;

        @NotBlank(message = "密码不能为空")
        private String password;

    }

}
